# OA 视图文件
# from OA import oa_bl
# from OA.models import *
from FlaskOA.OA import oa_bl
from FlaskOA.OA.models import *
# from models import Person,db
import hashlib
from flask import redirect,request,render_template,session
import os
import functools
def LoginValid(func):
    @functools.wraps(func)     #### 保存原来的函数名
    def inner(*args,**kwargs):
        # 校验规则
        cookie_username = request.cookies.get("username")
        cookie_userid = request.cookies.get("userid")
        session_userid = session.get("userid")
        if session_userid and cookie_userid and cookie_username:
            person = Person.query.filter(Person.id == int(cookie_userid),
                                         Person.username == cookie_username).first()
            if person:
                return func(*args,**kwargs)
        return redirect("/oa/login")
    return inner

def setPassword(password):
    md5 = hashlib.md5()
    md5.update(password.encode())
    result = md5.hexdigest()

    return result

# 职员管理页面
@oa_bl.route("/person")
@LoginValid
def person():
    # 获取到用户的信息
    person_list = Person.query.all()   ## 列表
    return render_template("person.html",**locals())

# 视图  接受请求参数
@oa_bl.route("/search_person")
def search_person():
    # 接受请求
    # 获取参数
    name = request.args.get("person_username")
    # 查询数据库   查询以name 开头的数据    模糊查询
    person_list = Person.query.filter(Person.nickname.like("{}%".format(name))).all()
    return render_template("person.html",**locals())


# 添加用户的页面
@oa_bl.route("/add_person",methods=["POST","GET"])
def add_person():
    # 处理get请求   返回页面
    # 处理post请求  接受请求的数据，将数据保存到数据中
    print(request.method)
    if request.method =="POST":
        print("处理post请求")
        # 获取post请求的数据
        username = request.form.get("username")
        password = request.form.get("password")
        nickname = request.form.get("nickname")
        gender = request.form.get("gender")
        age = request.form.get("age")
        # phone = request.form.get("phone")
        email = request.form.get("email")
        address = request.form.get("address")
        position_id = request.form.get("position_id")
        photo = request.files.get("photo")  ##获取图片
        person = Person()
        person.username = username
        person.password = setPassword(password)
        person.nickname = nickname
        person.gender = gender
        person.age = age
        # person.photo = photo
        person.email = email
        person.address = address
        # person.score = score
        person.p_position = 1
        if photo:
            base_dir = os.path.abspath(os.path.dirname(__file__))
            db_path = os.path.join("images",photo.filename)
            path = os.path.join("static",db_path)
            save_path = os.path.join(base_dir,path)
            # 保存到服务器
            # 保存数据库
            photo.save(save_path)
            person.photo = db_path
        person.save()
    return render_template("add_person.html")



@oa_bl.route("/person_details")
def person_details():
    # 处理get 请求
    # 接受参数  参数 用户id
    person_id = request.args.get("person_id")
    # 查询 用户对象
    person = Person.query.filter(Person.id ==person_id).first()
    return render_template("detail_person.html",**locals())

@oa_bl.route("/index")
@LoginValid
def index():
    """
    首页
    :return:
    """
    # 增加校验逻辑
    # 通过cookie 和sesion 校验
    return render_template("index.html")


@oa_bl.route("/login",methods=["GET","POST"])
def login():
    """
    登录页面
    :return:
    """
    ##处理get请求    返回登录页面
    #   处理 post请求   获取数据 校验数据
    if request.method == "POST":
        print(request.form)
        username = request.form.get("username")
        password = request.form.get("password")
        # 校验数据
        if username and password:
            # 校验数据库中是否存在
            person = Person.query.filter(Person.username == username,Person.password == setPassword(password)).first()
            #  判断
            if person:
                # 下发cookie 下发session  打开index 页面
                resp = redirect("/oa/index")
                # 下发cookie
                resp.set_cookie("username",username)
                resp.set_cookie("userid",str(person.id))
                # 下发session
                session["userid"] = person.id
                return resp


    return render_template("login.html")
@oa_bl.route("/logout")
def logout():
    # 删除 cookie 和  session
    #重定向到 登录页面
    resp = redirect("/login")
    resp.delete_cookie("username")
    resp.delete_cookie("userid")
    del session["userid"]
    return resp



